import urllib.request
import urllib.parse
import json
import time
import random
import hashlib

def fanyi(str):
	try:
		# url = 'http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule';
		url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&sessionFrom='
		data = {'i':str,
		        'rom':'AUTO',
		        'to':'AUTO',
		        'smartresult':'dict',
		        'client':'fanyideskweb',
		        'doctype':'json',
		        'version':'2.1',
		        'keyfrom':'fanyi.web',
		        'action':'FY_BY_REALTIME',
		        'typoResult':'true'
		        }


		data = urllib.parse.urlencode(data)

		headers = {'content-length':len(data),'Host': 'fanyi.youdao.com'}
		# 建立Request对象
		req = urllib.request.Request(url,data=bytes(data,encoding='utf-8'),headers=headers)
		# 打开网页
		res = urllib.request.urlopen(req)
		# 解析网页
		str = (res.read().decode('utf-8'))
		# 返回的东西是json格式
		myjson=json.loads(str)
		
		print('翻译结果为：“%s”          提示：可按__q退出'%myjson['translateResult'][0][0]['tgt'])
		
	except Exception as e:
		print(str)


if __name__=='__main__':
	while 1:
		str = input("请输入要搜索的词:")
		if str!='__q':
			fanyi(str)
		else:
			break
	